package com.projectplace.GUI;


/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import java.util.ArrayList;
import java.util.List;
import com.projectplace.ProjectPlace;
import com.projectplace.R;
import com.projectplace.SingeltonPPClient;
import com.projectplace.GUI.Callback.CacheCallbackInterface.ResponseMyProjects;
import com.projectplace.GUI.Database.CacheHelper;
import com.projectplace.GUI.adapter.Conversation_myProjects_Adapter;
import com.projectplace.api.OAUTH;
import com.projectplace.api.UserApi;
import com.projectplace.api.objectResponses.Project;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ListView;



public class Conversations extends ListActivity {
	
	private final static String LOG_TAG ="Conversations";
	private static ListActivity activity;
	
	private static ArrayList<Project> project;
	private static Conversation_myProjects_Adapter projectAdapter;
	//private static ListView projectList;
	private final String identifier="projectID";
	private static Handler hand;
	public static final String PREFS = "conversationFile";
	 
	//Android calls this method when Activity is Created
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);	
		
		setContentView(R.layout.list);
		hand = new Handler();
		project = new ArrayList<Project>();
		activity = this; 
		CacheHelper.getMyProjects(activity, new Handler(), new ResponseMyProjects() {
			public void onFail(Error err) {
				Log.d(LOG_TAG, err.getMessage());		
			}
			//Previous data could still be here so we clear the list and add everything from the cache
			public void onReceive(List<Project> cachedProjects) {
				project.clear();
				project.addAll(cachedProjects);
				projectAdapter = new Conversation_myProjects_Adapter(activity,project);
				activity.setListAdapter(projectAdapter);
			}
		}); 
	}
	//Listens for user clicks, have to parse from long since that's what the adapter is returning
	public void onListItemClick(ListView l,View v,int position,long id){
		String idOfClickedProject = String.valueOf(id);
		Log.d(LOG_TAG, idOfClickedProject);
		Intent intent = new Intent().setClass(this, ProjectConversation.class);
		intent.putExtra(identifier, idOfClickedProject);
		startActivity(intent);
	}
	
	public void onDestroy(){
		super.onDestroy();
		Log.d(LOG_TAG +LOG_TAG, "Destroying");
		//finish();
	}
	
	public void onPause(){
		super.onPause();
		CacheHelper.saveMyProjects(activity, project);
		
	}
	
	public void onResume(){
		super.onResume();
		SharedPreferences mSettings = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE);
		
		if(mSettings.contains(OAUTH.USER_TOKEN) && mSettings.contains(OAUTH.USER_SECRET)) {
			UserApi.getUserProjects(SingeltonPPClient.getInstance(), hand, new com.projectplace.api.Callback.Callback.ResponseListenerUserProjects() {
				public void SERVER_ERROR(Error err) {
					Log.d(LOG_TAG, "SERVER_ERROR");
				} 
				
				public void BAD_TOKEN_ERROR(Error err) {  
					SharedPreferences.Editor editor = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE).edit();
					
					//Clear the saved token and secret since they are deprecated if we end up here
					editor.remove(OAUTH.USER_TOKEN);
					Log.d(LOG_TAG, "Clearing OAuth Token");
					editor.remove(OAUTH.USER_SECRET);
					Log.d(LOG_TAG, "Clearing OAuth Secret");
					editor.commit();				
					Log.d(LOG_TAG, "Innan getUsrProjects");
					ProjectPlace ac;
					ac = (ProjectPlace)activity.getParent();
					ac.initiateOAUTH(); 
					Log.d(LOG_TAG, "de finns inte");
				}   
	
				public void onReceive(List<Project> userProjects) {
					Log.d(LOG_TAG, "I DO GET ANSWER!!"); 				
					if(project != null){
						//Not perfect! works as long as the user isn't part of many(above 10) projects since is freezes the ui thread
						for(Project p:userProjects){
							if(!project.contains(p))
								project.add(p);
						}
						if(projectAdapter == null){
							projectAdapter = new Conversation_myProjects_Adapter(activity,project);
							activity.setListAdapter(projectAdapter);
						}else{
							projectAdapter.notifyDataSetChanged();
							//cleanup();
						} 
					}
				} 
			});
		}
	} 
	
	private void cleanup(){
		SharedPreferences.Editor editor = getSharedPreferences(Conversations.PREFS, Context.MODE_PRIVATE).edit();
		
		for(Project c: project){
			
			editor.remove(c.getId());
			
		}
		editor.commit();
	}
}
